# import http.client
# import json
# import time
# from typing import Dict, List, Any, Optional
# from urllib.parse import urlencode


# def get_tianyi_share_data(share_code, access_code="", depth=5):
#     """
#     获取天翼云分享数据的主要方法
    
#     Args:
#         share_code (str): 分享码
#         access_code (str): 访问码，默认为空
#         depth (int): 遍历深度，默认为5
    
#     Returns:
#         dict: 包含以下字段的字典
#             - share_info: 分享相关的信息数据
#             - file_info: 文件列表（多层文件数据）
#             - statistics: 文件的相关统计信息
#             - success: 是否成功
#             - message: 结果消息
#     """
#     try:
#         # 获取分享信息
#         share_info = _get_share_info(share_code, access_code)
#         if not share_info:
#             return {
#                 'success': False,
#                 'message': '无法获取分享信息',
#                 'share_info': None,
#                 'file_info': [],
#                 'statistics': {}
#             }
        
#         # 初始化文件信息和统计数据
#         file_info = []
#         statistics = {
#             'total_files': 0,
#             'total_folders': 0,
#             'total_size': 0,
#             'file_types': {},
#             'max_depth_reached': 0
#         }
        
#         # 获取分享的基本信息
#         share_id = share_info.get('shareId')
#         root_file_id = share_info.get('fileId')
#         share_mode = share_info.get('shareMode', 3)
        
#         if not share_id or not root_file_id:
#             return {
#                 'success': False,
#                 'message': '分享信息不完整',
#                 'share_info': share_info,
#                 'file_info': [],
#                 'statistics': statistics
#             }
        
#         # 遍历文件目录
#         _traverse_directory(
#             share_id=str(share_id),
#             file_id=str(root_file_id),
#             share_dir_file_id=str(root_file_id),
#             share_mode=share_mode,
#             access_code=access_code,
#             current_depth=1,
#             max_depth=depth,
#             file_list=file_info,
#             stats=statistics,
#             path="/"
#         )
        
#         return {
#             'success': True,
#             'message': '数据提取成功',
#             'share_info': share_info,
#             'file_info': file_info,
#             'statistics': statistics
#         }
        
#     except Exception as e:
#         return {
#             'success': False,
#             'message': f'提取失败: {str(e)}',
#             'share_info': None,
#             'file_info': [],
#             'statistics': {}
#         }


# def extract_share_data(share_code: str, access_code: str = "", depth: int = 3) -> Dict[str, Any]:
#     """
#     提取天翼云盘分享数据
    
#     Args:
#         share_code: 分享码
#         access_code: 访问码（可选）
#         depth: 遍历深度，默认3层
    
#     Returns:
#         包含分享信息、文件列表和统计信息的字典
#     """
#     try:
#         # 首先获取分享基本信息
#         share_info = _get_share_info(share_code, access_code)
#         if not share_info:
#             return {
#                 "success": False,
#                 "error": "无法获取分享信息",
#                 "share_info": None,
#                 "file_info": [],
#                 "statistics": {}
#             }
        
#         # 提取关键信息
#         share_id = share_info.get('shareId')
#         root_file_id = share_info.get('fileId')
#         share_mode = share_info.get('shareMode', 3)
        
#         if not share_id or not root_file_id:
#             return {
#                 "success": False,
#                 "error": "分享信息不完整",
#                 "share_info": share_info,
#                 "file_info": [],
#                 "statistics": {}
#             }
        
#         # 递归获取文件列表
#         file_info = []
#         statistics = {
#             "total_files": 0,
#             "total_folders": 0,
#             "total_size": 0,
#             "file_types": {},
#             "max_depth_reached": 0
#         }
        
#         # 使用标准方法遍历
#         _traverse_directory(
#             share_id=str(share_id),  # 确保是字符串
#             file_id=str(root_file_id),
#             share_dir_file_id=str(root_file_id),
#             share_mode=share_mode,
#             access_code=access_code,
#             current_depth=0,
#             max_depth=depth,
#             file_list=file_info,
#             stats=statistics,
#             path="/"
#         )
        
#         return {
#             "success": True,
#             "share_info": share_info,
#             "file_info": file_info,
#             "statistics": statistics
#         }
        
#     except Exception as e:
#         return {
#             "success": False,
#             "error": f"提取数据时发生错误: {str(e)}",
#             "share_info": None,
#             "file_info": [],
#             "statistics": {}
#         }


# def _get_share_info(share_code: str, access_code: str = "") -> Optional[Dict[str, Any]]:
#     """
#     获取分享基本信息
#     """
#     try:
#         conn = http.client.HTTPSConnection("cloud.189.cn")
        
#         # 构建请求参数 - 使用正确的API接口
#         params = {
#             'noCache': str(time.time()),
#             'shareCode': share_code
#         }
#         if access_code:
#             params['accessCode'] = access_code
            
#         query_string = urlencode(params)
#         url = f"/api/open/share/getShareInfoByCodeV2.action?{query_string}"
        
#         headers = {
#             'Accept': 'application/json;charset=UTF-8',
#             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
#             'Referer': 'https://cloud.189.cn/'
#         }
        
#         conn.request("GET", url, "", headers)
#         response = conn.getresponse()
#         data = response.read().decode("utf-8")
#         conn.close()
        
#         result = json.loads(data)
#         if result.get('res_code') == 0:
#             # 检查返回的数据结构
#             data_content = result.get('data')
#             if data_content:
#                 return data_content
#             else:
#                 # 如果data为空，尝试从根级别获取信息
#                 share_info = {
#                     'shareId': result.get('shareId'),
#                     'fileId': result.get('fileId'),
#                     'shareMode': result.get('shareMode', 3),
#                     'shareName': result.get('fileName', '分享文件'),
#                     'shareCode': share_code,
#                     'creator': result.get('creator', {}),
#                     'fileSize': result.get('fileSize', 0),
#                     'isFolder': result.get('isFolder', True)
#                 }
                
#                 # 如果关键字段存在，返回构造的信息
#                 if share_info.get('shareId'):
#                     return share_info
#                 else:
#                     print("API返回成功但数据结构不完整，尝试备用方法")
#                     return _get_share_info_fallback(share_code, access_code)
#         else:
#             print(f"获取分享信息失败: {result.get('res_message', '未知错误')}")
#             # 如果第一个API失败，尝试直接获取文件列表
#             return _get_share_info_fallback(share_code, access_code)
            
#     except Exception as e:
#         print(f"获取分享信息时发生错误: {str(e)}")
#         # 尝试备用方法
#         return _get_share_info_fallback(share_code, access_code)


# def _traverse_directory_by_code(share_code: str, access_code: str, current_depth: int, 
#                                max_depth: int, file_list: List[Dict], stats: Dict, path: str):
#     """
#     通过分享码递归遍历目录
#     """
#     if current_depth > max_depth:
#         return
    
#     stats["max_depth_reached"] = max(stats["max_depth_reached"], current_depth)
    
#     try:
#         # 获取当前目录的文件列表 - 需要从分享信息中获取share_id
#         # 这里需要传递share_id，但当前函数没有这个参数，需要修改函数签名
#         files = []  # 暂时返回空列表，需要重构函数
        
#         if not files:
#             return
        
#         for file_item in files:
#             file_info = {
#                 "id": file_item.get('id'),
#                 "name": file_item.get('name'),
#                 "size": file_item.get('size', 0),
#                 "is_folder": file_item.get('isFolder', False),
#                 "create_time": file_item.get('createTime'),
#                 "last_op_time": file_item.get('lastOpTime'),
#                 "path": path + file_item.get('name', ''),
#                 "md5": file_item.get('md5', ''),
#                 "depth": current_depth,
#                 "download_url": file_item.get('downloadUrl'),
#                 "icon": file_item.get('icon'),
#                 "md5": file_item.get('md5'),
#                 "children": []
#             }
            
#             # 更新统计信息
#             if file_item.get('isFolder'):
#                 stats["total_folders"] += 1
#                 file_info["path"] += "/"
                
#                 # 如果是文件夹且未达到最大深度，递归遍历
#                 if current_depth < max_depth:
#                     print(f"正在遍历文件夹: {file_info['name']} (深度 {current_depth})")
#                     try:
#                         # 使用文件夹ID获取子文件夹内容
#                         sub_files = _get_directory_files_by_code(
#                             share_code=share_code,
#                             access_code=access_code,
#                             folder_id=file_item.get('id')
#                         )
                        
#                         if sub_files:
#                             print(f"在文件夹 {file_info['name']} 中找到 {len(sub_files)} 个项目")
                            
#                             # 处理子文件夹中的每个项目
#                             for sub_file in sub_files:
#                                 sub_file_info = {
#                                     "id": sub_file.get('id'),
#                                     "name": sub_file.get('name'),
#                                     "size": sub_file.get('size', 0),
#                                     "is_folder": sub_file.get('isFolder', False),
#                                     "create_time": sub_file.get('createTime'),
#                                     "last_op_time": sub_file.get('lastOpTime'),
#                                     "path": file_info["path"] + sub_file.get('name', ''),
#                                     "depth": current_depth + 1,
#                                     "download_url": sub_file.get('downloadUrl'),
#                                     "icon": sub_file.get('icon'),
#                                     "md5": sub_file.get('md5'),
#                                     "children": []
#                                 }
                                
#                                 if sub_file.get('isFolder'):
#                                     stats["total_folders"] += 1
#                                     sub_file_info["path"] += "/"
                                    
#                                     # 递归遍历更深层的子文件夹
#                                     if current_depth + 1 < max_depth:
#                                         _traverse_directory_by_code(
#                                             share_code=share_code,
#                                             access_code=access_code,
#                                             current_depth=current_depth + 2,
#                                             max_depth=max_depth,
#                                             file_list=sub_file_info["children"],
#                                             stats=stats,
#                                             path=sub_file_info["path"]
#                                         )
#                                 else:
#                                     stats["total_files"] += 1
#                                     stats["total_size"] += sub_file.get('size', 0)
                                    
#                                     # 统计文件类型
#                                     file_name = sub_file.get('name', '')
#                                     if '.' in file_name:
#                                         ext = file_name.split('.')[-1].lower()
#                                         stats["file_types"][ext] = stats["file_types"].get(ext, 0) + 1
                                
#                                 file_info["children"].append(sub_file_info)
                                
#                             stats["max_depth_reached"] = max(stats["max_depth_reached"], current_depth + 1)
#                         else:
#                             print(f"文件夹 {file_info['name']} 为空或无法访问")
#                     except Exception as e:
#                         print(f"无法访问文件夹 {file_info['name']}: {str(e)}")
#             else:
#                 stats["total_files"] += 1
#                 stats["total_size"] += file_item.get('size', 0)
                
#                 # 统计文件类型
#                 file_name = file_item.get('name', '')
#                 if '.' in file_name:
#                     ext = file_name.split('.')[-1].lower()
#                     stats["file_types"][ext] = stats["file_types"].get(ext, 0) + 1
            
#             file_list.append(file_info)
            
#     except Exception as e:
#         print(f"遍历目录时发生错误: {str(e)}")


# def _traverse_directory(share_id: str, file_id: str, share_dir_file_id: str, 
#                        share_mode: int, access_code: str, current_depth: int, 
#                        max_depth: int, file_list: List[Dict], stats: Dict, path: str):
#     """
#     递归遍历目录
#     """
#     if current_depth > max_depth:
#         return
    
#     stats["max_depth_reached"] = max(stats["max_depth_reached"], current_depth)
    
#     try:
#         # 获取当前目录的文件列表
#         files = _get_directory_files(
#             share_id=share_id,
#             file_id=file_id,
#             share_dir_file_id=share_dir_file_id,
#             share_mode=share_mode,
#             access_code=access_code
#         )
        
#         if not files:
#             return
        
#         for file_item in files:
#             file_info = {
#                 "id": file_item.get('id'),
#                 "name": file_item.get('name'),
#                 "size": file_item.get('size', 0),
#                 "is_folder": file_item.get('isFolder', False),
#                 "create_time": file_item.get('createTime'),
#                 "create_date": file_item.get('createDate'),  # 新增：创建日期
#                 "last_op_time": file_item.get('lastOpTime'),
#                 "file_cata": file_item.get('fileCata'),  # 新增：文件分类
#                 "media_type": file_item.get('mediaType'),  # 新增：媒体类型
#                 "orientation": file_item.get('orientation'),  # 新增：方向
#                 "rev": file_item.get('rev'),  # 新增：版本号
#                 "star_label": file_item.get('starLabel'),  # 新增：星标标签
#                 "path": path + file_item.get('name', ''),
#                 "depth": current_depth,
#                 "download_url": file_item.get('downloadUrl'),
#                 "icon": file_item.get('icon'),  # icon字段：仅视频和图片有此字段
#                 "md5": file_item.get('md5'),
#                 "children": []
#             }
            
#             # 更新统计信息
#             if file_item.get('isFolder'):
#                 stats["total_folders"] += 1
#                 file_info["path"] += "/"
                
#                 # 如果是文件夹且未达到最大深度，递归遍历
#                 if current_depth < max_depth:
#                     print(f"正在遍历文件夹: {file_info['name']} (深度 {current_depth})")
#                     try:
#                         # 使用正确的函数获取子文件夹内容
#                         sub_files = _get_directory_files(
#                             share_id=share_id,
#                             file_id=file_item.get('id'),
#                             share_dir_file_id=file_item.get('id'),
#                             share_mode=share_mode,
#                             access_code=access_code
#                         )
                        
#                         if sub_files:
#                             print(f"在文件夹 {file_info['name']} 中找到 {len(sub_files)} 个项目")
                            
#                             # 处理子文件夹中的每个项目
#                             for sub_file in sub_files:
#                                 sub_file_info = {
#                                     "id": sub_file.get('id'),
#                                     "name": sub_file.get('name'),
#                                     "size": sub_file.get('size', 0),
#                                     "is_folder": sub_file.get('isFolder', False),
#                                     "type": "folder" if sub_file.get('isFolder') else "file",
#                                     "create_time": sub_file.get('createTime'),
#                                     "create_date": sub_file.get('createDate'),  # 新增：创建日期
#                                     "last_op_time": sub_file.get('lastOpTime'),
#                                     "file_cata": sub_file.get('fileCata'),  # 新增：文件分类
#                                     "media_type": sub_file.get('mediaType'),  # 新增：媒体类型
#                                     "orientation": sub_file.get('orientation'),  # 新增：方向
#                                     "rev": sub_file.get('rev'),  # 新增：版本号
#                                     "star_label": sub_file.get('starLabel'),  # 新增：星标标签
#                                     "path": file_info["path"] + sub_file.get('name'),
#                                     "depth": current_depth + 1,
#                                     "download_url": sub_file.get('downloadUrl', ''),
#                                     "icon": sub_file.get('icon'),  # icon字段：仅视频和图片有此字段
#                                     "md5": sub_file.get('md5'),
#                                     "children": []
#                                 }
                                
#                                 if sub_file.get('isFolder'):
#                                     stats["total_folders"] += 1
#                                     sub_file_info["path"] += "/"
                                    
#                                     # 递归遍历子文件夹
#                                     if current_depth + 1 < max_depth:
#                                         _traverse_directory(
#                                             share_id=share_id,
#                                             file_id=sub_file.get('id'),
#                                             share_dir_file_id=sub_file.get('id'),
#                                             share_mode=share_mode,
#                                             access_code=access_code,
#                                             current_depth=current_depth + 1,
#                                             max_depth=max_depth,
#                                             file_list=sub_file_info["children"],
#                                             stats=stats,
#                                             path=sub_file_info["path"]
#                                         )
#                                 else:
#                                     stats["total_files"] += 1
#                                     stats["total_size"] += sub_file.get('size', 0)
                                    
#                                     # 统计文件类型
#                                     file_name = sub_file.get('name', '')
#                                     if '.' in file_name:
#                                         ext = file_name.split('.')[-1].lower()
#                                         stats["file_types"][ext] = stats["file_types"].get(ext, 0) + 1
                                
#                                 file_info["children"].append(sub_file_info)
                                
#                             stats["max_depth_reached"] = max(stats["max_depth_reached"], current_depth + 1)
#                         else:
#                             print(f"文件夹 {file_info['name']} 为空或无法访问")
#                     except Exception as e:
#                         print(f"无法访问文件夹 {file_info['name']}: {str(e)}")
#             else:
#                 stats["total_files"] += 1
#                 stats["total_size"] += file_item.get('size', 0)
                
#                 # 统计文件类型
#                 file_name = file_item.get('name', '')
#                 if '.' in file_name:
#                     ext = file_name.split('.')[-1].lower()
#                     stats["file_types"][ext] = stats["file_types"].get(ext, 0) + 1
            
#             file_list.append(file_info)
            
#     except Exception as e:
#         print(f"遍历目录时发生错误: {str(e)}")


# def _get_share_info_fallback(share_code: str, access_code: str = "") -> Optional[Dict[str, Any]]:
#     """
#     备用方法：直接尝试获取分享文件列表来推断分享信息
#     """
#     try:
#         # 尝试使用分享码作为shareId直接获取文件列表
#         files = _get_directory_files_by_code(share_code, access_code)
#         if files:
#             # 如果能获取到文件列表，构造基本的分享信息
#             return {
#                 'shareId': share_code,
#                 'fileId': '0',  # 根目录
#                 'shareMode': 3,
#                 'shareName': '分享文件',
#                 'shareCode': share_code
#             }
#         else:
#             # 即使没有文件，也返回基本信息，可能是空分享或需要密码
#             return {
#                 'shareId': share_code,
#                 'fileId': '0',  # 根目录
#                 'shareMode': 3,
#                 'shareName': '分享文件',
#                 'shareCode': share_code
#             }
#     except Exception as e:
#         return None


# def _get_directory_files_by_code(share_code: str, access_code: str = "", page_num: int = 1, 
#                                  page_size: int = 60, folder_id: str = None, share_id: str = None, share_mode: int = 3) -> List[Dict[str, Any]]:
#     """
#     通过分享码直接获取文件列表
#     """
#     try:
#         conn = http.client.HTTPSConnection("cloud.189.cn")
        
#         # 构建请求参数
#         params = {
#             'iconOption': 5,
#             'orderBy': 'lastOpTime',
#             'descending': 'true',
#             'pageNum': page_num,
#             'pageSize': page_size
#         }
        
#         # 添加必要的参数
#         if share_id:
#             params['shareId'] = share_id
#         if share_mode:
#             params['shareMode'] = share_mode
#         if share_code:
#             params['shareCode'] = share_code
#         if access_code:
#             params['accessCode'] = access_code
            
#         # 如果指定了文件夹ID，添加相关参数
#         if folder_id:
#             params['fileId'] = folder_id
#         else:
#             # 根目录需要使用默认的fileId
#             if share_id:
#                 params['fileId'] = share_id  # 使用share_id作为根目录的fileId
            
#         query_string = urlencode(params)
#         url = f"/api/open/share/listShareDir.action?{query_string}"
        
#         headers = {
#             'Accept': 'application/json;charset=UTF-8',
#             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
#             'Referer': 'https://cloud.189.cn/'
#         }
        
#         conn.request("GET", url, "", headers)
#         response = conn.getresponse()
#         data = response.read().decode("utf-8")
#         conn.close()
        
#         if folder_id:
#             print(f"子文件夹 {folder_id} API响应: {data[:200]}...")  # 调试信息
        
#         result = json.loads(data)
#         if result.get('res_code') == 0:
#             file_list_ao = result.get('data', {}).get('fileListAO', {})
#             return file_list_ao.get('content', [])
#         else:
#             error_msg = result.get('res_message', '未知错误')
#             if folder_id:
#                 print(f"获取子文件夹列表失败: {error_msg}")
#             else:
#                 print(f"获取根目录文件列表失败: {error_msg}")
#             print(f"API响应: {data[:300]}...")  # 显示更多调试信息
#             return []
            
#     except Exception as e:
#         if folder_id:
#             print(f"获取子文件夹列表时发生错误: {str(e)}")
#         return []


# def _get_directory_files(share_id: str, file_id: str, share_dir_file_id: str, 
#                         share_mode: int, access_code: str, page_num: int = 1, 
#                         page_size: int = 60) -> List[Dict[str, Any]]:
#     """
#     获取目录下的文件列表
#     """
#     try:
#         conn = http.client.HTTPSConnection("cloud.189.cn")
        
#         # 构建请求参数
#         params = {
#             'noCache': str(time.time()),
#             'pageNum': page_num,
#             'pageSize': page_size,
#             'fileId': file_id,
#             'shareDirFileId': share_dir_file_id,
#             'isFolder': 'true',
#             'shareId': share_id,
#             'shareMode': share_mode,
#             'iconOption': 5,
#             'orderBy': 'lastOpTime',
#             'descending': 'true'
#         }
        
#         if access_code:
#             params['accessCode'] = access_code
            
#         query_string = urlencode(params)
#         url = f"/api/open/share/listShareDir.action?{query_string}"
        
#         headers = {
#             'Accept': 'application/json;charset=UTF-8',
#             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
#             'Referer': 'https://cloud.189.cn/'
#         }
        
#         conn.request("GET", url, "", headers)
#         response = conn.getresponse()
#         data = response.read().decode("utf-8")
#         conn.close()
        
#         result = json.loads(data)
#         if result.get('res_code') == 0:
#             file_list_ao = result.get('fileListAO', {})
            
#             # 获取文件列表和文件夹列表
#             file_list = file_list_ao.get('fileList', [])
#             folder_list = file_list_ao.get('folderList', [])
            
#             # 合并文件和文件夹，并标记类型
#             combined_list = []
            
#             # 处理文件
#             for file_item in file_list:
#                 file_item['isFolder'] = False
#                 combined_list.append(file_item)
            
#             # 处理文件夹
#             for folder_item in folder_list:
#                 folder_item['isFolder'] = True
#                 folder_item['size'] = 0  # 文件夹大小设为0
#                 combined_list.append(folder_item)
            
#             return combined_list
#         else:
#             print(f"获取文件列表失败: {result.get('res_message', '未知错误')}")
#             return []
            
#     except Exception as e:
#         print(f"获取文件列表时发生错误: {str(e)}")
#         return []


# # 测试函数
# def test_extract_share_data():
#     """
#     测试分享数据提取功能
#     """
#     share_code = "r2In2efYBrMf"
#     access_code = ""
#     depth = 2
    
#     print(f"开始提取分享数据...")
#     print(f"分享码: {share_code}")
#     print(f"访问码: {access_code if access_code else '无'}")
#     print(f"遍历深度: {depth}")
#     print("-" * 50)
    
#     result = extract_share_data(share_code, access_code, depth)
    
#     if result["success"]:
#         print("✅ 数据提取成功!")
#         print(f"📁 总文件夹数: {result['statistics']['total_folders']}")
#         print(f"📄 总文件数: {result['statistics']['total_files']}")
#         print(f"💾 总大小: {result['statistics']['total_size']} 字节")
#         print(f"🔍 实际遍历深度: {result['statistics']['max_depth_reached']}")
#         print(f"📊 文件类型统计: {result['statistics']['file_types']}")
#     else:
#         print(f"❌ 数据提取失败: {result['error']}")
    
#     return result


# if __name__ == "__main__":
#     import sys
    
#     # 默认参数
#     default_share_code = "r2In2efYBrMf"
#     default_access_code = ""
#     default_depth = 2
    
#     # 从命令行参数获取，如果没有则使用默认值
#     share_code = sys.argv[1] if len(sys.argv) > 1 else default_share_code
    
#     # 处理访问码参数（可能为空字符串或"-"表示空）
#     if len(sys.argv) > 2:
#         access_code = sys.argv[2] if sys.argv[2] not in ["", "-"] else default_access_code
#     else:
#         access_code = default_access_code
    
#     # 处理深度参数
#     if len(sys.argv) > 3:
#         try:
#             depth = int(sys.argv[3])
#         except ValueError:
#             print(f"警告: 深度参数 '{sys.argv[3]}' 不是有效数字，使用默认值 {default_depth}")
#             depth = default_depth
#     else:
#         depth = default_depth
    
#     # 显示使用说明
#     if len(sys.argv) == 1:
#         print("使用方法: python share_utils.py [分享码] [访问码] [遍历深度]")
#         print(f"默认参数: 分享码={default_share_code}, 访问码='{default_access_code}', 遍历深度={default_depth}")
#         print("注意: 访问码为空时可以用 '-' 表示")
#         print("")
    
#     print(f"正在提取分享码 {share_code} 的数据...")
#     print(f"参数: 访问码='{access_code}', 遍历深度={depth}")
#     result = get_tianyi_share_data(share_code, access_code, depth)
    
#     if result['success']:
#         print("\n✅ 数据提取成功!")
#         print(f"📁 总文件夹数: {result['statistics']['total_folders']}")
#         print(f"📄 总文件数: {result['statistics']['total_files']}")
#         print(f"💾 总大小: {result['statistics']['total_size']} 字节")
#         print(f"🔍 实际遍历深度: {result['statistics']['max_depth_reached']}")
#         print(f"📊 文件类型统计: {result['statistics']['file_types']}")
        
#         # 显示分享信息
#         share_info = result['share_info']
#         print(f"\n📋 分享信息:")
#         print(f"   分享名称: {share_info.get('shareName', 'N/A')}")
#         print(f"   分享ID: {share_info.get('shareId', 'N/A')}")
#         print(f"   文件ID: {share_info.get('fileId', 'N/A')}")
#         print(f"   分享模式: {share_info.get('shareMode', 'N/A')}")
        
#         # 显示文件树
#         file_info = result['file_info']
#         if file_info:
#             # 计算总文件数（包括子文件夹中的文件）
#             def count_all_items(items):
#                 count = 0
#                 for item in items:
#                     count += 1
#                     if item.get('children'):
#                         count += count_all_items(item['children'])
#                 return count
            
#             total_items = count_all_items(file_info)
#             print(f"\n🌳 文件树结构 (共{total_items}个):")
            
#             # 递归打印文件树
#             def print_tree(items, prefix=""):
#                 for i, item in enumerate(items):
#                     is_last = (i == len(items) - 1)
#                     current_prefix = "└── " if is_last else "├── "
                    
#                     # 显示文件/文件夹信息
#                     file_type = "📁" if item.get('is_folder') else "📄"
#                     name = item.get('name', '')
#                     size_info = f" ({item.get('size', 0)} 字节)" if not item.get('is_folder') else ""
#                     depth_info = f" [深度{item.get('depth', 0)}]" if item.get('depth', 0) > 1 else ""
                    
#                     print(f"{prefix}{current_prefix}{file_type} {name}{size_info}{depth_info}")
                    
#                     # 递归打印子文件夹内容
#                     if item.get('children'):
#                         next_prefix = prefix + ("    " if is_last else "│   ")
#                         print_tree(item['children'], next_prefix)
            
#             print_tree(file_info)
#         else:
#             print("\n📄 未找到任何文件")
        

#         print("\n✅ 全量数据!")
#         import json
#         print("\n✅ 数据提取成功! " + json.dumps(result, indent=2, ensure_ascii=False))
        
#     else:
#         print(f"\n❌ 数据提取失败: {result['message']}")